package com.kky.pp.activity.me.info

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import com.custom.base.base.SDEventManager
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.kky.pp.common.Constant
import com.kky.pp.R
import com.kky.pp.base.GenderPreferListBean
import com.kky.pp.base.TitleBasePresenterImpl
import com.kky.pp.bean.TagBean
import com.kky.pp.bean.TOListBean
import com.kky.pp.bean.UserPhotoBean
import com.kky.pp.popup.CustomSelectorPopup
import com.kky.pp.popup.SelectInterestPopup
import com.kky.pp.entity.UserPhotoEntity
import com.kky.pp.entity.UserProfileEntity
import com.kky.pp.popup.SelectDataPopup
import com.kky.pp.popup.SelectGenderPopup
import com.kky.pp.popup.SelectHeightPopu
import com.kky.pp.view.date.DateSelectStyle
import com.kky.pp.util.DateUtils
import com.kky.pp.util.DensityUtil
import com.kky.pp.util.UploadPhoto
import com.kky.pp.view.Loading.LoadingDialog
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import io.rong.imkit.SpName
import io.rong.imkit.event.EnumEventTag
import java.util.Calendar
import java.util.stream.Collectors


class ProfileInfoPresenter : TitleBasePresenterImpl<ProfileInfoContact.View>() {

    override fun initBundle(bundle: Bundle) {
        mView?.apply {
            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                override fun addBody(requestBody: OkHttpBodyEntity) {
                    requestBody.setPost(Constant.user_info_url)
                }
            }, object : SDOkHttpResoutCallBack<UserProfileEntity>() {
                override fun onSuccess(entity: UserProfileEntity) {
                    viewUpImageViews.setData(entity.data.imagesV2)
                    evEditName.text = entity.data.nickName
                    val d = Calendar.getInstance()
                    d.time =
                        DateUtils.getDate(entity.data.birthday, DateSelectStyle.MM_DD_YYYY.valus)
                    Calendar.getInstance().get(Calendar.MONTH) - 1

                    upDateNowIwant(entity.data.userWant, tvNowIwant)
                    upDateYouAccpet(
                        entity.data.youAccept,
                        viewYouAcceptList,
                        tvEmptyTagYouAccept
                    )
                    tvBirth.text = getMoth(entity.data.birthday).replace("/", "-")
                    imgInterestsAdd.setOnClickListener {
                        SelectInterestPopup(
                            mActivity,
                            entity.data.interests ?: arrayListOf(),
                            object : SelectInterestPopup.onCallBack {
                                override fun onCallback(tags: MutableList<TagBean>) {
                                    val checkedTags: MutableList<String> = ArrayList()
                                    val checkedTagsBean: MutableList<TagBean> = ArrayList()
                                    repeat(tags.size) {
                                        if (tags[it].check) {
                                            checkedTags.add(tags[it].interest)
                                            checkedTagsBean.add(tags[it])
                                        }
                                    }
                                    entity.data.interests = checkedTags
                                    viewTagCloud.setTags(checkedTags)
                                    interestsEmpty.isVisible =
                                        entity.data.interests.isEmpty()
                                    viewTagCloud.isVisible =
                                        entity.data.interests.isNotEmpty()
                                    saveProfileInfo(interests = checkedTagsBean)
                                }
                            })
                    }
                    interestsEmpty.isVisible = entity.data.interests.isNullOrEmpty()
                    viewTagCloud.isVisible = !entity.data.interests.isNullOrEmpty()
                    viewTagCloud.setTags(entity.data.interests)
                    val lookingFor = entity.data.lookingFor
                    (mActivity as ProfileInfoActivity).setGenderText(entity.data.gender)
                    (mActivity as ProfileInfoActivity).setLookingForDrawables(lookingFor)

                    if (TextUtils.isEmpty(entity.data.inchHeight)) {
                        tvHeight.text = mActivity.getString(R.string.enter_your_height)
                    } else {
                        tvHeight.text = entity.data.inchHeight
                    }
                    txtAboutMeValue.text = entity.data.aboutMe

                    date_of_birth_container.setOnClickListener {
                        SelectDataPopup(
                            mActivity,
                            tvBirth.text.toString(),
                            object : SelectDataPopup.OnCallBack {
                                @SuppressLint("SetTextI18n")
                                override fun callBack(data: String) {
                                    entity.data.birthday = data
                                    tvBirth.text = data
                                    saveProfileInfo(birthday = DateUtils.replace(data))
                                }

                            }).showPopupWindow()
                    }
                    looking_for_container.setOnClickListener {
                        SelectGenderPopup(
                            mActivity,
                            entity.data.lookingFor,
                            object : SelectGenderPopup.OnCallBack {
                                override fun callBack(seeking: Int) {
                                    entity.data.lookingFor = seeking
                                    (mActivity as ProfileInfoActivity).setLookingForDrawables(
                                        seeking
                                    )
                                    saveProfileInfo(lookingFor = seeking.toString())
                                }

                            }).showPopupWindow()
                    }
                    heightContainer.setOnClickListener {
                        SelectHeightPopu(
                            mActivity,
                            entity.data.inchHeight,
                            object : SelectHeightPopu.OnCallBack {
                                override fun callBack(date: String) {
                                    entity.data.inchHeight = date
                                    tvHeight.text = date
                                    saveProfileInfo(height = date)
                                }

                            }).showPopupWindow()
                    }

                    imgIWantAdd.setOnClickListener(
                        IWantClickListener(
                            this@ProfileInfoPresenter,
                            entity.data.userWant,
                            tvNowIwant
                        )
                    )
                    imgYourAcceptAdd.setOnClickListener(
                        YouAcceptInClickListener(
                            this@ProfileInfoPresenter,
                            viewYouAcceptList,
                            tvEmptyTagYouAccept,
                            entity.data.youAccept
                        )
                    )

                }

                override fun onFailure(code: Int, msg: String) {

                }
            })
        }
        super.initBundle(bundle)
    }

    class IWantClickListener(
        val presenter: ProfileInfoPresenter,
        val userWant: MutableList<GenderPreferListBean>,
        val tvNowIwant: TextView
    ) : View.OnClickListener {
        override fun onClick(v: View?) {
            CustomSelectorPopup()
                .buildConfig(presenter.mActivity)
                .setTitle(presenter.mActivity.getString(R.string.now_i_want))
                .setDatas(userWant)
                .setMultipleChoice(false)
                .setOnClickListener(object : CustomSelectorPopup.OnClickListener {
                    override fun save(
                        dialog: CustomSelectorPopup,
                        allDataList: MutableList<GenderPreferListBean>?,
                        selectDataList: MutableList<GenderPreferListBean>?
                    ) {
                        selectDataList?.get(0)?.code?.let { it1 ->
                            presenter.saveProfileInfo(userWant = it1) {
                                userWant.clear()
                                allDataList?.stream()?.forEach {
                                    userWant.add(it)
                                }
                                presenter.upDateNowIwant(
                                    selectDataList,
                                    tvNowIwant
                                )
                            }
                        }
                    }

                    override fun close() {
                    }

                    override fun selected() {
                    }

                })
                .show()
        }

    }

    class YouAcceptInClickListener(
        val presenter: ProfileInfoPresenter,
        val viewYouAccpetList: LinearLayout,
        val emptyAccept: TextView,
        val youAccept: MutableList<GenderPreferListBean>
    ) : View.OnClickListener {
        override fun onClick(v: View?) {
            CustomSelectorPopup()
                .buildConfig(presenter.mActivity)
                .setTitle(presenter.mActivity.getString(R.string.you_accept))
                .setDatas(youAccept)
                .setMultipleChoice(true)
                .setOnClickListener(object : CustomSelectorPopup.OnClickListener {
                    override fun save(
                        dialog: CustomSelectorPopup,
                        allDataList: MutableList<GenderPreferListBean>?,
                        selectDataList: MutableList<GenderPreferListBean>?
                    ) {
                        val codes = arrayListOf<Long>()
                        selectDataList?.forEach { codes.add(it.code) }
                        presenter.saveProfileInfo(youAccept = codes) {
                            youAccept.clear()
                            allDataList?.stream()?.forEach {
                                youAccept.add(it)
                            }
                            presenter.upDateYouAccpet(
                                selectDataList,
                                viewYouAccpetList,
                                emptyAccept
                            )
                        }
                    }

                    override fun close() {
                    }

                    override fun selected() {
                    }

                })
                .show()
        }

    }

    private fun upDateYouAccpet(
        dataList: MutableList<GenderPreferListBean>?,
        viewYouAccpetList: LinearLayout,
        emptyAccept: TextView
    ) {
        val youAccpet = dataList?.stream()?.filter { v -> v.selected == 1 }?.collect(
            Collectors.toList()
        )
        viewYouAccpetList.removeAllViews()
        viewYouAccpetList.isVisible = (youAccpet?.size ?: 0) > 0
        emptyAccept.isVisible = (youAccpet?.size ?: 0) <= 0
        youAccpet?.stream()?.forEach {
            val textAccpet = TextView(mActivity)
            textAccpet.setTextColor(mActivity.getColor(R.color.white))
            textAccpet.textSize = 14f
            textAccpet.typeface = mActivity.resources.getFont(R.font.interregular)

            textAccpet.setPadding(
                DensityUtil.dip2px(mActivity, 15f),
                DensityUtil.dip2px(mActivity, 10f), 0,
                DensityUtil.dip2px(mActivity, 10f)
            )
            it.value.let { it1 -> textAccpet.text = it1 }
            viewYouAccpetList.addView(textAccpet)
        }

    }

    private fun upDateNowIwant(
        dataList: MutableList<GenderPreferListBean>?,
        tvNowIwant: TextView,
    ) {
        val userWant =
            dataList?.stream()?.filter { v -> v.selected == 1 }?.collect(
                Collectors.toList()
            )
        if (userWant != null && userWant.size > 0) {
            tvNowIwant.text = userWant[0].value
            tvNowIwant.isVisible = true
        } else {
            tvNowIwant.isVisible = false
        }
    }

    override fun onBackClick() {
        finish()
    }


    fun deleteImage() {
        val viewUpImageView = mView?.viewUpImageViews
        val userPhotoBean = viewUpImageView?.userImages?.get(viewUpImageView.photoSelectPosition)
        LoadingDialog.showLoading(mActivity, "upload...")
        userPhotoBean?.imageUrl?.let {
            userPhotoBean?.imageCode?.let { it1 ->
                savePhonto(
                    it1,
                    it,
                    3,
                    0
                )
            }
        }// 删除照片
    }

    private fun addImage(selectPosition: Int, selectList: ArrayList<LocalMedia>?) {
        mView?.apply {
            selectList?.forEach {
                val path = when {
                    it.isCompressed -> {
                        it.compressPath
                    }

                    it.isCut -> {
                        it.cutPath
                    }

                    else -> {
                        it.realPath
                    }
                }
                if (path.contains(".mp4", true) || it.mimeType.contains(
                        ".3gp",
                        true
                    ) || it.mimeType.contains(".mov", true)
                ) {
                    showToast("pls upload photo.")
                    return
                }
                val userPhotoBeans = viewUpImageViews.userImages
                val userPhotoBean = userPhotoBeans[selectPosition]
                val opType = if (TextUtils.isEmpty(userPhotoBean.imageUrl)) 1 else 2
                val imageCode = if (opType == 1) "" else {
                    userPhotoBean.imageCode
                }

                LoadingDialog.showLoading(mActivity, "upload...")
                UploadPhoto.uploadFileNewPhoto(
                    mActivity,
                    path,
                    imageCode,
                    object : UploadPhoto.OnLister {
                        override fun onSuccess(successPath: String, imageCode: String) {
//                        val userImages = viewUpImageView.userImages
//                        val selectPosition = (mActivity as ProfileInfoActivity).nowSelectImagePosition
//                        userImages?.removeAt(selectPosition)
//                        userImages?.add(selectPosition,successPath)
//                        userImages?.let { it1 -> viewUpImageView.setData(it1) }
                            val opType = if (TextUtils.isEmpty(imageCode)) 1 else 2
                            if (opType == 2) {
                                var selectPosition = 0
                                for (i in 0 until userPhotoBeans.size) {
                                    if (userPhotoBeans[i].imageCode == imageCode) {
                                        selectPosition = i
                                        break
                                    }
                                }
                                savePhonto(
                                    imageCode,
                                    successPath,
                                    opType,
                                    if (selectPosition == 0) 1 else 0
                                )
                            } else {
                                var lastPosition = 0
                                for (i in 0 until userPhotoBeans.size) {
                                    if (userPhotoBeans[i].imageUrl == "") {
                                        lastPosition = i
                                        break
                                    }
                                }
                                savePhonto(
                                    "",
                                    successPath,
                                    opType,
                                    if (viewUpImageViews.photoSelectPosition == 0) 1 else 0
                                )
                            }

                        }

                        override fun fail() {
                            var lastPosition = 0
                            LoadingDialog.dismissLoading()
                            showToast("upload error,pls try again")
                        }

                    })
            }
        }
    }

    fun savePhonto(
        imageCode: String,
        imageUrl: String,
        opType: Int,
        avatarFlag: Int
    ) {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.user_changeImage_url)
                requestBody.add("opType", opType)//1-新增 2-修改 3-删除
                requestBody.add("imageCode", imageCode)
                requestBody.add("imageUrl", imageUrl)
                requestBody.add("avatarFlag", avatarFlag)//1-是 0-否
                requestBody.add("type", 1)
            }
        }, object : SDOkHttpResoutCallBack<UserPhotoEntity>() {
            override fun onSuccess(entity: UserPhotoEntity) {
                val viewUpImageView = mView?.viewUpImageViews
                val userPhotoBeans = viewUpImageView?.userImages ?: ArrayList()
                if (opType == 1) {
                    mView?.apply {
                        if (entity.data != null) {
                            var lastPosition = 0
                            for (i in 0 until userPhotoBeans.size) {
                                if (userPhotoBeans[i].imageUrl == "") {
                                    lastPosition = i
                                    break
                                }
                            }
                            userPhotoBeans[lastPosition].imageUrl = entity.data.imageUrl
                            userPhotoBeans[lastPosition].imageLoadUrl = entity.data.imageUrl
                            userPhotoBeans[lastPosition].imageCode = entity.data.imageCode
                            userPhotoBeans[lastPosition].loading = false
                            viewUpImageViews.userImages = userPhotoBeans
                            viewUpImageViews.upDataItemImage(lastPosition)
                        }
                    }
                } else if (opType == 2) {
                    if (entity.data != null) {
                        var lastPosition = 0
                        for (i in 0 until userPhotoBeans.size) {
                            if (userPhotoBeans[i].imageCode == entity.data.imageCode) {
                                lastPosition = i
                                break
                            }
                        }
                        userPhotoBeans[lastPosition].imageUrl = entity.data.imageUrl
                        userPhotoBeans[lastPosition].imageLoadUrl = entity.data.imageUrl
                        userPhotoBeans[lastPosition].imageCode = entity.data.imageCode
                        userPhotoBeans[lastPosition].loading = false
                        mView?.viewUpImageViews?.userImages = userPhotoBeans
                        mView?.viewUpImageViews?.upDataItemImage(lastPosition)
                    }
                    if (avatarFlag == 1) {
                        if (entity.data.imageUrl != BaseConfig.getInstance.getString(
                                SpName.avatarUrl,
                                ""
                            )
                        ) {
                            SDEventManager.post(
                                entity.data.imageUrl,
                                EnumEventTag.REFRESH_ME_BOTTOM_AVATAR.ordinal
                            )
                        }
                    }
                } else if (opType == 3) {
                    val position = mView?.viewUpImageViews?.photoSelectPosition ?: 0
                    userPhotoBeans.removeAt(position)
                    mView?.viewUpImageViews?.setData(userPhotoBeans)
                }

            }

            override fun onFailure(code: Int, msg: String) {
                showToast(msg)
            }

            override fun onFinish() {
                super.onFinish()
                LoadingDialog.dismissLoading()
            }
        })
    }

    fun saveProfileInfo(
        nickName: String = "",
        birthday: String = "",
        lookingFor: String = "",
        interests: MutableList<TagBean> = arrayListOf(),
        aboutMe: String = "",
        socialConnections: String = "",
        height: String = "",
        hideHeight: Boolean = false,
        turnOns: ArrayList<TOListBean> = arrayListOf(),
        userWant: Long = 0,
        youAccept: ArrayList<Long> = arrayListOf(),
        success: (() -> Unit?)? = null
    ) {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.user_user_change_url)
                if (userWant != 0L) {
                    requestBody.add("userWant", userWant)
                }
                if (youAccept.size > 0) {
                    requestBody.add("youAccept", youAccept)
                }
                if (nickName != "") {
                    requestBody.add("nickName", nickName)
                }
                if (birthday != "") {
                    requestBody.add("birthday", birthday)
                }
                if (lookingFor != "") {
                    requestBody.add("lookingFor", lookingFor)
                }
                if (interests.isNotEmpty()) {
                    val list = arrayListOf<Int>()
                    repeat(interests.size) {
                        list.add(interests[it].interestCode)
                    }
                    requestBody.add("interests", list)
                }
                if (aboutMe != "") {
                    requestBody.add("aboutMe", aboutMe)
                }
                if (socialConnections != "") {
                    requestBody.add("socialConnections", socialConnections)
                }
                if (height != "") {
                    if (height == "0") {
                        requestBody.add("hideHeight", hideHeight)
                    } else {
                        requestBody.add("height", height)
                    }
                }
                if (turnOns.isNotEmpty()) {
                    val list = arrayListOf<Int>()
                    repeat(turnOns.size) {
                        if (turnOns[it].selected == 1) {
                            list.add(turnOns[it].turnOnsCode)
                        }
                    }
                    requestBody.add("turnOnsList", list)
                }

            }
        }, object : SDOkHttpResoutCallBack<UserProfileEntity>() {
            override fun onSuccess(entity: UserProfileEntity) {
                success?.invoke()
                mView?.apply {
                    if (lookingFor != "") {
                        SDEventManager.post(EnumEventTag.INDEX_REFRESH_DATA.ordinal)
                    }
                    if (nickName != "") {
                        SDEventManager.post(EnumEventTag.MY_REFRESH.ordinal)
                    }
                }
            }

            override fun onFailure(code: Int, msg: String) {
                showToast(msg)
            }
        })
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList = PictureSelector.obtainSelectorList(data)
                    mView?.viewUpImageViews?.photoSelectPosition?.let { addImage(it, selectList) }
                }
            }
        }
    }

    fun getMoth(date: String): String {
        val moth = date.substring(0, 2).toInt()
        return DateUtils.getMonth()[moth - 1] + date.substring(2, date.length)
    }

}